//
//  AdviceViewController.m
//  FruitsAndHealthy
//
//  Created by appying_wxj on 14/11/14.
//  Copyright (c) 2014年 appying_wxj. All rights reserved.
//

#import "AdviceViewController.h"
#import "AdviceDetailViewController.h"
@interface AdviceViewController ()

@end

@implementation AdviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLab.text = @"食用锦囊";
    
    // 初始化控件
    [self initAdVice];
    
    if ([AllRequest checkNet]) {
       [MBProgressHUD showHUDAddedTo:self.adviceTableView animated:YES];
        [self getAdviceDate];
        [self.adviceTableView reloadData];
        [MBProgressHUD hideHUDForView:self.adviceTableView animated:YES];
    }
}

-(void)initAdVice{
    // 导航条左边的按钮
    [self.leftButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _adviceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, kScreen_Height-64) style:UITableViewStylePlain];
    _adviceTableView.backgroundColor = [UIColor whiteColor];
    _adviceTableView.delegate = self;
    _adviceTableView.dataSource = self;
    _adviceTableView.rowHeight = 60;
    _adviceTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _adviceTableView.separatorStyle = NO;
    [self.view addSubview:_adviceTableView];
    [self setExtraCellLineHidden:_adviceTableView];
    
    // 2.集成刷新控件
    [self setupRefresh];

}
// 获取数据
-(void)getAdviceDate{
   
    _adviceAllArray = [[NSMutableArray alloc] init];
    _adviceTitleArray = [[NSMutableArray alloc] init];
    _adviceContentsArray = [[NSMutableArray alloc] init];
    
    
    AVQuery *fruits = [AVQuery queryWithClassName:@"advice"];
    [fruits findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {// 请求成功
            _adviceAllArray = [NSMutableArray arrayWithArray:objects];
            for (int i = 0; i < _adviceAllArray.count; i++) {
                AVObject *fruitsName = [_adviceAllArray objectAtIndex:i];
                [_adviceTitleArray addObject:[fruitsName objectForKey:@"headline"]];
                [_adviceContentsArray addObject:[fruitsName objectForKey:@"contents"]];
            }
            [_adviceTableView reloadData];
        } else {// 请求失败
            // Log details of the failure
           
        }
    }];

}
/**
 *  集成刷新控件
 */
- (void)setupRefresh {
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_adviceTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // 自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_adviceTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _adviceTableView.headerPullToRefreshText = @"下拉可以刷新了";
    _adviceTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    _adviceTableView.headerRefreshingText = @"正在刷新中";
    
    _adviceTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    _adviceTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    _adviceTableView.footerRefreshingText = @"正在加载中";
}
#pragma mark 开始进入刷新状态
// 下拉刷新
- (void)headerRereshing {
    //    // 1.添加数据
    //    for (int i = 0; i<5; i++) {
    ////        [self.fakeData insertObject:[self string] atIndex:0];
    //        [self getAllDate];
    //    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_adviceTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_adviceTableView headerEndRefreshing];
    });
}
// 上提加载
- (void)footerRereshing {
    // 1.添加假数据
    //    for (int i = 0; i<5; i++) {
    ////        [_fruitsTableView addObject:[self string]];
    //        [self getAllDate];
    //    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_adviceTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_adviceTableView footerEndRefreshing];
    });
}

//隐藏表格多余分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView {
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

#pragma mark------UITableViewDataSource  delegate----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _adviceTitleArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    else{
        while ([cell.contentView.subviews lastObject]!=nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    // 分割的线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(10, 59.5, kScreen_Width-20, 0.5)];
    line.backgroundColor = [UIColor colorWithRed:0.89 green:0.93 blue:0.75 alpha:1];
    [cell.contentView addSubview:line];
    
    if (indexPath.row<_adviceAllArray.count) {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, kScreen_Width-20, 40)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.text = [_adviceTitleArray objectAtIndex:indexPath.row];
        titleLabel.textColor = [UIColor colorWithRed:0.66 green:0.73 blue:0.02 alpha:1];
        titleLabel.font = [UIFont systemFontOfSize:18];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:titleLabel];
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       
                       AdviceDetailViewController *AdviceDetail = [[AdviceDetailViewController alloc] init];
                       AdviceDetail.adviceDetailContent = [_adviceContentsArray objectAtIndex:indexPath.row];
                       AdviceDetail.adviceDetailTitle = [_adviceTitleArray objectAtIndex:indexPath.row];
                       [self presentViewController:AdviceDetail animated:YES completion:nil];
                       
                   });
}

#pragma mark------ButtonClick-------
-(void)backButtonClick:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
